package com.bi.design.config;

import com.bi.design.enums.GlobalResultEnum;
import com.bi.design.exception.GlobalException;
import com.bi.design.pojo.TokenTools;
import com.bi.design.tools.ApiResult;
import com.bi.design.tools.JsonUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UrlPathHelper;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 此种方式可针对白名单
 */
@Slf4j
@Component
public class AuthFilter extends OncePerRequestFilter {

    // 白名单地址url地址
    private final static String[] whiteUrls = new String[]{
            /* 静态资源 前端页面*/
            "/index.html",
            "/favicon.ico",
            "/js/**",
            "/css/**",
            "/static/**",
            "/sys-user/add-or-edit",
            "/login",
            "/file/**",
            "/source/**",};

    private final static List<String> uris = Arrays.asList(whiteUrls);

    private final PathMatcher pathMatcher = new AntPathMatcher();

    private final UrlPathHelper urlPathHelper = new UrlPathHelper();

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //获取请求你ip后的全部路径
        String lookupPath = urlPathHelper.getLookupPathForRequest(req);
        //过滤掉不需要的Xss校验的地址
        for (String uri : uris) {
            if (pathMatcher.match(uri, lookupPath)) {
                chain.doFilter(req, response);
                return;
            }
        }
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        String token = req.getHeader("token");
        if (StringUtils.isBlank(token)) {
            //设置body
            JsonUtils.renderJson(response, ApiResult.status(GlobalResultEnum.TOKEN_EXPIRE));
            return;
        }
        // 验证token
        try {
            TokenTools.validateToken(token);
        } catch (GlobalException e) {
            JsonUtils.renderJson(response, ApiResult.status(GlobalResultEnum.TOKEN_EXPIRE));
            return;
        }
        // 放行
        chain.doFilter(req, response);
    }
}
